const express = require('express');
const cors = require('cors');
const path = require('path');
const { NewMessage } = require('telegram/events');
const { sendCode, login, logoutFromSession, createClientFromSession, getUserGroups, sendPrivateMessageToUser } = require('./telegramAuth'); // 修正路径
const { error } = require('console');
const { watch } = require('fs/promises');
const app = express();
var eventHandler = null;
const WebSocket = require('ws');
const GroupMessageListener = require('./GroupMessageListener');
app.use(express.json());
const telegramClients = new Map(); // token => TelegramClient
const wsConnections = new Map();   // ws => { token, eventHandler }
// 1. 初始化 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8081 }, () => {
  console.log('WebSocket 服务器已启动，监听 ws://127.0.0.1:8081');
});
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
const { queryAllKeyWord, insertKeyWrod, delKeyWrod } = require("./service/KeywordService")
const { getRandomString } = require("./utils/tools")
// const { addListenes, delListenes, getListenes, getListenerClientById, listenerStop, listenerStart, listenerIsState, } = require("./service/ListenersService")
const { getMessageRouter } = require('./messageRouter'); // 确保引入共享路由器
const { addListenes, getListenerClientById, listenerStart, listenerStop, getListenes ,getSizeInfo,delListener} = require('./service/listenerManager');
const {queryAllMes ,resetSendMsg} = require("./service/MessageSendingRecord")
const fs = require('fs');
const yaml = require('js-yaml'); 

let PORT = {};
try {
    const fileContents = fs.readFileSync(path.resolve(__dirname, './config1.yml'), 'utf8');
    const config = yaml.load(fileContents);
    console.log(config.servicePort)
    PORT = config.servicePort
   
    // config = config;
    // console.log('✅ 配置加载成功:', tgConfig);
} catch (e) {
    console.error('❌ 读取配置失败:', e);
}


// 2. WebSocket 连接处理
wss.on('connection', async (ws, req) => {
  const token = req.headers['token'] || '';
  console.log('WebSocket 连接建立:', token);
 
  // 确保 Telegram 客户端已初始化
  let client = telegramClients.get(token);

    try {
      client = await createClientFromSession(token);
      telegramClients.set(token, client);
      console.log('Telegram 客户端已初始化:', token);
    } catch (error) {
      console.error('初始化 Telegram 客户端失败:', error);
      ws.close(1011, 'Telegram 客户端初始化失败');
      return;
    }

  // 定义事件处理器
   eventHandler = async (event) => {
      try {
        if (event.isPrivate) {
          const message = event.message;
          const sender = await message.getSender();
          const callbackData = {
            messageId: message.id.toString(),
            senderId: sender.id.toString(),
            text: message.message,
            date: message.date,
            isOutgoing: message.out,
          };
          ws.send(JSON.stringify(callbackData)); // 推送消息到客户端
          console.log('wss服务端发送消息');
        }
      }catch (error) {
        console.error('事件处理失败:', error);
        // 可选：重新订阅事件
        client.removeEventHandler(eventHandler);
        client.addEventHandler(eventHandler, new NewMessage({}));
      }
  };
 
  // 订阅消息事件
  client.addEventHandler(eventHandler, new NewMessage({}));
  wsConnections.set(ws, { token, eventHandler });
  // 清理逻辑：WebSocket 关闭时取消订阅
  ws.on('close', () => {
    const { eventHandler } = wsConnections.get(ws) || {};
    if (eventHandler) {
      client.removeEventHandler(eventHandler); // 移除事件监听
      wsConnections.delete(ws);
    }
    console.log('WebSocket 连接关闭:', token);
  });
});


// 测试路由
app.get('/test', (req, res) => {
  return res.send({ name: "测试2" });
});

// 首页
app.get('/', (req, res) => {
  return res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 登录处理
app.post('/login', async (req, res) => {
  const { phone, pwd, code } = req.body;
  console.log({ phone, pwd, code });
  const client = await login(phone, code, pwd)
  if (client == null || client == "" || client == undefined) {
    return res.status(400).json({ error: "登录失败" })
  }
  return res.send(client);
});
 // 3. HTTP 接口（可选，用于初始化客户端）

//发送验证码
app.post('/codes', async (req, res) => {
  try {
    const phone = req.body.phone?.trim(); // ✅ 防止空格
    const phoneRegex = /^\+\d{8,15}$/;

    if (!phone) {
      return res.status(400).json({ error: "❌ 缺少手机号参数" });
    }

    if (!phoneRegex.test(phone)) {
      return res.status(400).json({ error: "❌ 手机号格式不正确，必须包含国家码" });
    }

    console.log("📱 获取手机号：", phone);
    const phoneCodeHash = await sendCode(phone);

    return res.json({
      message: "✅ 验证码已发送",
      phoneCodeHash
    });
  } catch (error) {
    console.error("发送验证码出错：", error);
    return res.status(500).json({ error: "❌ 内部服务器错误" });
  }
});

//注销登录
app.post('/logout', async (req, res) => {
  let userToken = req.body.token
  console.log("获取用户的Token：", userToken)
  let flag = logoutFromSession(userToken)
  if (flag) {
    return res.send({ msg: 'ok' })
  }
  return res.status(400).json({ error: "注销失败" })
})


app.get('/query/groups', async (req, res) => {
  // console.log(req.headers.token)
  let token = req.headers.token
  let client = await createClientFromSession(token)
  // console.log(client)
  let groups = await getUserGroups(client)
  // console.log(groups)
  return res.send({ msg: 'ok', data: groups })
})

// 消息回调
app.post('/msg', async (req, res) => {
  const token = req.headers.token ;
  try {
    if (!telegramClients.has(token)) {
      const client = await createClientFromSession(token);
      telegramClients.set(token, client);
    }
    res.send('Telegram 客户端已就绪');
  } catch (error) {
    res.status(500).send('初始化失败: ' + error.message);
  }
});



// app.post('/groups/listening', async (req, res) => {
//   try {
//     const token = req.headers.token;

//     // 从请求体里拿到 id 和 accessHash（注意 accessHash 是字符串，需转 BigInt）
//     const id = Number(req.body.id);
//     const accessHash = BigInt(req.body.accessHash);
//     const phone = req.body.phone
//     const title = req.body.title
//     console.log('token:', token);
//     console.log('channelId:', id);
//     console.log('accessHash:', accessHash);

//     // 创建 client 并开始监听
//     const client = await createClientFromSession(token); // 确保你已实现这个函数，且返回 TelegramClient 实例
//     let result = await listening(client, id, accessHash, phone, title);

//     res.send({ msg: result });
//   } catch (err) {
//     console.error('❌ 监听出错：', err);
//     res.status(500).send({ error: err.message });
//   }
// });

// app.post("/groups/config/start", async (req, res) => {
//   let id = req.body.id
//   console.log("获取监听客户端Id：", id)
//   let listenerClient = await getListenerClientById(id)
//   // console.log(lis)
//   // return
//   // console.log("获取监听客户端：",listenerClient)

//   if (listenerClient == null) {
//     return res.status(404).json({ error: "获取监听客户端失败" })
//   }

//   await listenerStart(listenerClient);

//   return res.send({ msg: '开启监听成功' })
// })


app.post('/groups/listening', async (req, res) => {
  const { id, accessHash, phone, title } = req.body;
  const token = req.headers.token;
  const client = await createClientFromSession(token);
  const result = await addListenes({ id, accessHash, phone, title, client });
  res.send({ msg: result });
});

app.post('/groups/config/start', async (req, res) => {
  const id = req.body.id;
  const listenerClient = getListenerClientById(id);
  if (!listenerClient) return res.status(404).send({ error: '未找到监听器' });
  await listenerStart(listenerClient);
  res.send({ msg: '开启监听成功' });
});

app.post('/groups/config/stop', async (req, res) => {
  const id = req.body.id;
  const listenerClient = getListenerClientById(id);
  if (!listenerClient) return res.status(404).send({ error: '未找到监听器' });
  await listenerStop(listenerClient);
  res.send({ msg: '停止监听成功' });
});

app.get('/groups/list', async (req, res) => {
  const data = getListenes();
  res.send({ data });
});



app.get("/groups/size",(req,res)=>{
  return res.send(getSizeInfo())
})

app.post("/groups/config/del",async (req,res)=>{
  let id = req.body.id
  let result = await delListener(id)
  return res.send(result)
})

app.post("/send/user/msg", async (req, res) => {
  let toekn = req.headers.token
  let userId = req.body.userId
  let msg = req.body.msg
  let client = await createClientFromSession(toekn)
  client.addEventHandler(eventHandler, new NewMessage({}));
  await sendPrivateMessageToUser(client, userId, "", msg)
  return res.send({ msg: 'ok' })
})

app.get("/query/keywrods", async (req, res) => {
  let result = await queryAllKeyWord()

  if (!result) {
    return res.status(404).json({ error: "数据为空" })
  }

  return res.send(result)
})

app.post("/del/keywrod", async (req, res) => {
  let id = req.query.id
  let result = await delKeyWrod(id)
  return res.send(result)
})

app.post("/in/keywrod", async (req, res) => {
  let key = req.body.wrod;
  let content = req.body.content
  console.log(req.body)
  console.log(key)
  console.log(content)

  let result = await insertKeyWrod(key, content)
  return res.send(result)
})

app.get("/query/listening", (req, res) => {
  let result = getListenes()
  if (!result) {
    return res.status(404).json({ error: '数据为空' })
  }
  return res.send(result)
})


app.get("/record/msg/list",async (req,res)=>{
  let result = await queryAllMes()
  if(!result){
    return res.status(404).json({error : '数据为空'})
  }
  return res.send(result)
})

app.post("/record/msg/resetsend",async (req,res)=>{
  let toekn = req.headers.token
  let id = req.body.id
  // console.log(toekn)
  // console.log(id)
  let client = await createClientFromSession(toekn)
  let result = await resetSendMsg(id,client)
  console.log(result)
  if(!result){
    return res.status(404).send({msg : '发送失败'})
  }
  return res.send({msg : '发送成功'})
})


/**
 * 监听群聊函数
 * @param {TelegramClient} client 已连接的 Telegram 客户端实例
 * @param {number} id 群聊 ID（channelId）
 * @param {string|bigint} accessHash 群聊的 accessHash
 * @param {string} phone 用户手机号
 * @param {string} title 群聊名称  
 */
async function listening(client, id, accessHash, phone, title) {
  if (!client || typeof client.addEventHandler !== 'function') {
    throw new Error('❌ 参数 client 无效或不是 TelegramClient 实例');
  }

  if (!id || !accessHash) {
    throw new Error('❌ 缺少必要的群组 id 或 accessHash');
  }

  await client.connect();

  // ✅ 获取或初始化共享路由器（全局单例）
  const router = getMessageRouter(client);

  // ✅ 创建监听器实例（传入 router）
  const listenerClient = new GroupMessageListener(client, router, id, accessHash);

  // ✅ 添加监听器到管理器
  let listeners = {
    title,
    client,
    id,
    accessHash,
    listenerClient,
    phone,
    uuid: getRandomString()
  };

  const result = await addListenes(listeners);

  // ✅ 启动监听（非常重要）
  await listenerStart(listenerClient);

  return result;
}



app.listen(PORT, () => {
  console.log(`服务已经启动地址为：http://localhost:${PORT}`);
});

